from django import setup
import os
import sys
import redis

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings')
setup()

from utils.getPublicData import *
from django.core.cache import cache

def main():
    print("=== 测试Redis连接和缓存功能 ===")
    
    try:
        # 1. 直接测试Redis连接
        print("\n1. 测试Redis连接")
        redis_client = redis.Redis(host='127.0.0.1', port=6379, db=1)
        pong = redis_client.ping()
        print(f"Redis连接成功: {pong}")
        
        # 2. 测试Django缓存
        print("\n2. 测试Django缓存")
        cache.set('test_key', 'test_value', timeout=300)
        value = cache.get('test_key')
        print(f"缓存测试结果: {value == 'test_value'}")
        
        # 3. 测试数据缓存
        print("\n3. 测试数据缓存")
        print("第一次获取averageCity(应从数据库读取):")
        data1 = getaverageCity()
        print(f"数据长度: {len(data1)}")
        
        print("\n检查缓存:")
        cached = cache.get('averageCity')
        print(f"是否已缓存: {cached is not None}")
        
        print("\n第二次获取averageCity(应从缓存读取):")
        data2 = getaverageCity()
        print(f"数据是否一致: {data1 == data2}")
        
        # 4. 查看所有缓存的键
        print("\n4. 当前Redis中的所有键:")
        all_keys = redis_client.keys('*')
        for key in all_keys:
            key_str = key.decode('utf-8') if isinstance(key, bytes) else key
            key_type = redis_client.type(key).decode('utf-8')
            print(f"键: {key_str}, 类型: {key_type}")
        
        # 5. 测试带参数的查询缓存
        print("\n5. 测试带参数的查询缓存")
        range_value = '5-7k'
        data = gettypeSalary(range_value)
        print(f"数据长度: {len(data)}")
        cache_key = f'typeSalary_{range_value}'
        print(f"是否已缓存: {cache.get(cache_key) is not None}")
        
    except Exception as e:
        print(f"错误: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
